<template>
	<view class="all">
		<u-loading-page :loading="isloading"></u-loading-page>
		<view>
			<!-- <scroll-view scroll-y="true" class="content">
				<view class="me">
					<view class="mes" v-for="item,index in chatContents" :key="item.id">
						<image :src="item.fromUserId===id?myAvatar:toAvatar" mode="aspectFill"
							:class="item.fromUserId===id?'myavatar':'toavatar'"></image>
						<view :class="item.fromUserId===id?'msg':'tomsg'">
							<text>{{item.message}}</text>
						</view>
					</view>
				</view>
			</scroll-view> -->
			<view class="content">
				<view class="me" :class="isPull?'mrtop':''">
					<view class="mes" v-for="item,index in chatContents" :key="item.id">
						<image :src="item.fromUserId===id?myAvatar:toAvatar" mode="aspectFill"
							:class="item.fromUserId===id?'myavatar':'toavatar'"
							@click="goTopage1(item.fromUserId===id)"></image>
						<view :class="item.fromUserId===id?'msg':'tomsg'" @longpress="copy(item.message)">
							<text>{{item.message}}</text>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="send">
			<textarea placeholder="输入信息" fixed maxlength="-1" cursor-spacing="10" :show-confirm-bar="false" auto-height
				fontSize="15px" :focus="false" :value="msg" clearable @keyboardheightchange="khc"
				@confirm="$u.throttle(clickRequest,100)" @input="inputt" class="input" confirm-type="send"
				confirm-hold="true"></textarea>
			<view class="btn" @touchend.stop="$u.throttle(clickRequest,100)">
				发送
			</view>
		</view>
	</view>

</template>

<script>
	export default {
		data() {
			return {
				toUserId: '',
				toUserName: '',
				toAvatar: '',
				toOriginAvatar: '',
				socketTask: null,
				userinfo: {},
				myAvatar: '',
				id: '',
				chatContents: [],
				tips: "发送",
				msg: '',
				isConnected: false,
				scrollTop: 20000000,
				isloading: true,
				KeyboardHeight: 0,
				KeyTop: 1,
				isPull: false
			}
		},
		onLoad() {
			this.init()
			setTimeout(() => {
				this.isloading = false
			}, 1000)
		},
		onUnload() {
			this.socketTask.close()
		},
		onPageScroll: function(e) { //nvue暂不支持滚动监听，可用bindingx代替
			uni.$u.debounce(() => {
				this.scrollTop = e.scrollTop
			}, 500)
		},
		methods: {
			async init() {
				try {
					let ImgUrl = getApp().globalData.ImgUrl
					const page = await getCurrentPages()
					let x = page.length - 1
					let options = page[x].options
					this.toUserId = options.toId
					this.toUserName = options.toName
					this.toOriginAvatar = options.toAvatar
					this.toAvatar = ImgUrl + options.toAvatar
					let userInfo = uni.getStorageSync('userinfo')
					this.userinfo = userInfo
					this.id = userInfo.id
					this.myAvatar = ImgUrl + userInfo.avatar
					this.getChat(options.toId)
					uni.setNavigationBarTitle({
						title: this.toUserName
					});

					uni.onKeyboardHeightChange(res => {
						if (res.height == 0) {
							setTimeout(() => {
								uni.pageScrollTo({
									scrollTop: 2000000, //滚动到页面的目标位置（单位px）
									duration: 150 //滚动动画的时长，默认300ms，单位 ms
								});
							}, 550)
						}
						this.KeyboardHeight = res.height
					})
				} catch (res) {
					// console.log(res)
				}
			},
			async getChat(id) {
				let BaseUrl = getApp().globalData.BaseUrl
				let token = uni.getStorageSync('token')
				await uni.request({
					url: BaseUrl + '/chat/chatMessage',
					method: "POST",
					header: {
						'Content-Type': 'application/json',
						'token': token
					},
					data: JSON.stringify({
						page: 1,
						limit: 10000,
						toUserId: id
					}),
					success: (res) => {
						// // console.log(res)
						this.chatContents = res.data.data
						if (!this.isPull) {
							this.$nextTick(() => {
								uni.pageScrollTo({
									scrollTop: 2000000, //滚动到页面的目标位置（单位px）
									duration: 0 //滚动动画的时长，默认300ms，单位 ms
								});
							})
						}
						this.connectSocketInit();
					}
				})
			},
			goTopage1(isMe) {
				if (!isMe) {
					uni.navigateTo({
						url: '/pages/Personal/Personal?userId=' + this.toUserId + '&avatar=' + this
							.toOriginAvatar +
							'&username=' + this.toUserName
					})
				}
			},
			// 进入这个页面的时候创建websocket连接【整个页面随时使用】
			connectSocketInit() {
				let token = uni.getStorageSync('token')
				let toId = this.toUserId
				let Id = this.id
				let socketUrl = getApp().globalData.socketUrl

				// 创建一个this.socketTask对象【发送、接收、关闭socket都由这个对象操作】
				if (!this.isConnected) {
					this.socketTask = uni.connectSocket({
						// 【非常重要】必须确保你的服务器是成功的,如果是手机测试千万别使用ws://127.0.0.1:9099【特别容易犯的错误】
						url: socketUrl + toId + '/' + Id + '/' + token,
						method: "CONNECT",
						success: (data) => {
							// console.log("websocket连接成功", data);
							this.isConnected = true;
						},
					});
				}
				// 消息的发送和接收必须在正常连接打开中,才能发送或接收【否则会失败】
				this.socketTask.onOpen((res) => {
					// console.log("WebSocket连接正常打开中...！", res);
				})
				this.socketTask.onMessage((res) => {
					let data = JSON.parse(res.data)
					let msg = data.message
					// console.log("收到服务器内容：", msg);
					this.getChat(this.toUserId)
				});
				// 这里仅是事件监听【如果socket关闭了会执行】
				this.socketTask.onClose((res) => {
					// console.log("已经被关闭了", res)
				})
			},
			inputt(e) {
				uni.$u.debounce(() => {
					this.msg = e.detail.value
				}, 100)
			},
			clickRequest() {
				if (!this.msg) {
					uni.showToast({
						title: "内容为空",
						icon: "none"
					})
					return;
				}
				if (this.isConnected) {
					// websocket的服务器的原理是:发送一次消息,同时返回一组数据【否则服务器会进去死循环崩溃】
					this.socketTask.send({
						data: JSON.stringify({
							message: this.msg,
						}),
						async success(res) {
							// console.log("消息发送成功", res);
						},
					});
					setTimeout(() => {
						this.msg = ''
						this.getChat(this.toUserId)
					}, 100)
				}
				const query = uni.createSelectorQuery().in(this);
				query.select('.content').boundingClientRect(data => {
					// console.log("得到布局位置信息" + JSON.stringify(data));
					// console.log("我要变大dada了")
					if (data.height > 700) {
						// console.log("我要变大了")
						setTimeout(() => {
							this.isPull = false
						}, 150)
						// uni.pageScrollTo({
						// 	scrollTop: 0, //滚动到页面的目标位置（单位px）
						// 	duration: 300 //滚动动画的时长，默认300ms，单位 ms
						// });
					} else {
						setTimeout(() => {
							this.isPull = true
						}, 150)
						uni.pageScrollTo({
							scrollTop: 0, //滚动到页面的目标位置（单位px）
							duration: 500 //滚动动画的时长，默认300ms，单位 ms
						});
					}
				}).exec();
			},
			khc() {
				uni.pageScrollTo({
					scrollTop: 2000000, //滚动到页面的目标位置（单位px）
					duration: 150 //滚动动画的时长，默认300ms，单位 ms
				});
				uni.onKeyboardHeightChange(res => {
					if (res.height == 0) {
						setTimeout(() => {
							uni.pageScrollTo({
								scrollTop: 2000000, //滚动到页面的目标位置（单位px）
								duration: 150 //滚动动画的时长，默认300ms，单位 ms
							});
						}, 250)
					}
					this.KeyboardHeight = res.height
				})
				const query = uni.createSelectorQuery().in(this);
				query.select('.content').boundingClientRect(data => {
					this.KeyTop = data.top
					// console.log("得到布局位置信息" + JSON.stringify(data));
					// console.log(this.KeyboardHeight, data.top, data.height)
					if (this.KeyboardHeight > 0 && data.top == 0 && data.height < 450) {
						// console.log("我要变了")
						setTimeout(() => {
							this.isPull = true
						}, 150)
						uni.pageScrollTo({
							scrollTop: 0, //滚动到页面的目标位置（单位px）
							duration: 500 //滚动动画的时长，默认300ms，单位 ms
						});
					}
					if (this.KeyboardHeight == 0) {
						setTimeout(() => {
							this.isPull = false
						}, 250)
					}
				}).exec();
			},
			copy(value) {
				uni.setClipboardData({
					data: value, //要被复制的内容
					success: () => { //复制成功的回调函数
						uni.showToast({ //提示
							title: '复制成功',
							icon: 'none'
						})
					}
				});
			},
		}
	}
</script>

<style scoped lang="scss">
	.all {
		background-color: #ececec;
		height: 100%;
	}

	.content {
		background-color: #ececec;

		.mrtop {
			padding-top: 535upx;
		}

		.me {
			background-color: #ececec;
			transition: padding-top 0.6s;
			width: 100%;
			height: 100%;
			margin-bottom: 80upx;

			.mes {
				// display: flex;
				min-height: 100upx;
				width: 100%;
				overflow: auto;
				margin-bottom: 5upx;

				.msg {
					background-color: #fff;
					box-shadow: 0 0 10upx #888;
					font-size: 34upx;
					border-radius: 10upx;
					padding: 10upx;
					float: right;
					max-width: 80vw;
					margin-right: 10upx;
					margin-top: 10upx;
					margin-bottom: 10upx;
				}

				.myavatar {
					height: 80upx;
					width: 80upx;
					border-radius: 50%;
					box-shadow: 0 0 5upx #888;
					float: right;
					margin-top: 10upx;
					margin-right: 20upx;
				}

				.tomsg {
					background-color: #fff;
					box-shadow: 0 0 10upx #888;
					font-size: 34upx;
					border-radius: 10upx;
					padding: 10upx;
					float: left;
					max-width: 80vw;
					margin-top: 10upx;
					margin-bottom: 10upx;
				}


				.toavatar {
					height: 80upx;
					width: 80upx;
					border-radius: 50%;
					box-shadow: 0 0 5upx #888;
					float: left;
					margin-top: 10upx;
					margin-left: 20upx;
					margin-right: 10upx;
				}
			}
		}
	}

	.send {
		min-height: 80upx;
		padding: 10upx;
		background-color: #fff;
		box-shadow: 0 0 8upx #888;
		border-top-left-radius: 10upx;
		border-top-right-radius: 10upx;
		z-index: 999;
		width: 100%;
		position: fixed;
		bottom: 0;
		display: flex;
		align-items: center;

		.input {
			width: 81%;
			padding-left: 2%;
			// margin-bottom: 10upx;
		}

		.btn {
			width: 15%;
			height: 60upx;
			padding: 5upx 10upx;
			background-color: $color;
			font-size: 30upx;
			color: white;
			border-radius: 10upx;
			position: absolute;
			top: 10upx;
			right: 10upx;
			display: flex;
			align-items: center;
			justify-content: center;
		}
	}
</style>
